package com.example.easypoi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.easypoi.config.CommonResult;
import com.example.easypoi.model.Maintain;
import com.example.easypoi.model.MaintainDto;
import com.example.easypoi.model.MaintainDtoList;
import com.example.easypoi.service.MaintainService;
import com.example.easypoi.util.ReadPatientExcelUtil;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: 朱超
 * @createDate: 2023/3/28
 * @version: 1.0
 * @remark：备注
 */
@Api(tags = "导入文件")
@RestController
@RequestMapping("/maintain")
public class MaintainController {

    @Resource
    private MaintainService maintainService;

    @GetMapping("/addMaintain")
    public CommonResult<?> addMaintain(@RequestParam("file") MultipartFile file) {
        try {
            return CommonResult.success(maintainService.addMaintain(file));
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 导出 e
     *
     * @return
     */
    @ApiOperation("导出")
    @GetMapping("/createExcle")
    public CommonResult<?> createExcle() {
        //第一步创建workbook
        HSSFWorkbook wb = new HSSFWorkbook();

        //第二步创建sheet
        HSSFSheet sheet = wb.createSheet("资阳");

        //第三步创建行row:添加表头0行
        //4个参数依次为：开始行，结束行，开始列，结束列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
        HSSFRow row = sheet.createRow(0);

        HSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("嘎嘎嘎");
        HSSFCellStyle style = wb.createCellStyle();
//        style.setAlignment(HSSFCellStyle);  //居中

        HSSFRow row1 = sheet.createRow(1);

        //第四步创建单元格
        HSSFCell cell = row1.createCell(0);         //第一个单元格
//        cell.setCellValue("序号id");                  //设定值
//        cell.setCellStyle(style);                   //内容居中

//        cell = row1.createCell(1);                   //第二个单元格
        cell.setCellValue("公司名称");
        cell.setCellStyle(style);

        cell = row1.createCell(1);                   //第三个单元格
        cell.setCellValue("法人");
        cell.setCellStyle(style);

        cell = row1.createCell(2);                   //第四个单元格
        cell.setCellValue("手机号");
        cell.setCellStyle(style);

        cell = row1.createCell(3);                   //第五个单元格
        cell.setCellValue("地址");
        cell.setCellStyle(style);


        cell = row1.createCell(4);                   //第五个单元格
        cell.setCellValue("个体标识 1->个体 0->企业");
        cell.setCellStyle(style);

        cell = row1.createCell(5);                   //第五个单元格
        cell.setCellValue("市");
        cell.setCellStyle(style);

        cell = row1.createCell(6);                   //第五个单元格
        cell.setCellValue("区");
        cell.setCellStyle(style);
        //第五步插入数据
        Maintain tbHkhb = new Maintain();
        List<Maintain> list = maintainService.queryList();
        for (int i = 0; i < list.size(); i++) {
            //创建行
            row = sheet.createRow(i + 2);
            //创建单元格并且添加数据
//            row.createCell(0).setCellValue(simpleDateFormat.format(list.get(i).getHbsj()));
//            row.createCell(0).setCellValue(list.get(i).getMaintainId());
            row.createCell(0).setCellValue(list.get(i).getEnterpriseName());
            row.createCell(1).setCellValue(list.get(i).getLegalPerson());
            row.createCell(2).setCellValue(list.get(i).getPhone());
            row.createCell(3).setCellValue(list.get(i).getAddress());
            row.createCell(4).setCellValue(list.get(i).getIndividual());
            row.createCell(5).setCellValue(list.get(i).getCity());
            row.createCell(6).setCellValue(list.get(i).getDistrict());
        }
        //第六步将生成excel文件保存到指定路径下
        try {
            File file = new File("C:/Users/lenovo/Desktop/表.xls");
            if (!file.exists()) {
                FileOutputStream fout = new FileOutputStream("C:/Users/lenovo/Desktop/资阳信息表记录表.xls");
                wb.write(fout);
                fout.close();
            } else {
                FileOutputStream fout = new FileOutputStream("C:/Users/lenovo/Desktop/资阳信息表记录表(1).xls");
                wb.write(fout);
                fout.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.success("ok");
    }

    @ApiOperation("添加企业信息")
    @PostMapping("/excelExport")
    public CommonResult test(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam("name") String name) {
        long startTime = System.currentTimeMillis();
        List<String> list = new ArrayList();
        Map<String, Object> res = new HashMap<>();
        int row = 1;
        int rowSuccess = 0;
        Integer errorCount = 0;
        QueryWrapper<Maintain> wrapper;
//        ReadExcel readExcel = new ReadExcel();
        List<MaintainDto> excelInfo = ReadPatientExcelUtil.getExcelInfo(file);
        List<MaintainDto> excelInfoList = new ArrayList<>();
        excelInfo.stream().forEach(e -> {
            MaintainDto dto = new MaintainDto();
            BeanUtils.copyProperties(e, dto);
            dto.setIndividual("0");//企业
            //判断是否包含该字
            boolean contains = e.getAddress().contains(name);
            if (contains) {
                dto.setCity(name);
                String[] split = e.getAddress().split(name);
                dto.setDistrict(split[1]);
            } else {
                //截取字符串 市
                boolean con = e.getAddress().contains("市");
                if (con) {
                    String[] split = e.getAddress().split("市");
                    String substring = split[0].substring(split[0].length() - 2, split[0].length());
                    System.out.println(substring + "市");
                    dto.setDistrict(split[1]);
                    dto.setCity(substring + "市");
                } else {
                    dto.setDistrict(e.getAddress());
                    dto.setCity(name);
                }
            }
            excelInfoList.add(dto);
        });
        MaintainDtoList maintainDtoList = new MaintainDtoList();
        maintainDtoList.setMaintainDtoList(excelInfoList);
        maintainService.addMaintainaddMaintain(maintainDtoList);
//        maintainService.addMaintainSSS(excelInfo);
//        for (MaintainDto patientInfo : excelInfo) {
//            Maintain maintain = new Maintain();
//            BeanUtils.copyProperties(patientInfo, maintain);

////            System.out.println(patientInfo);
//            wrapper = new QueryWrapper<>();
//            row++;
//            patientInfo.setEnterpriseName(patientInfo.getEnterpriseName());
////            wrapper.eq("healing_Id", patientInfo.getHealingId());
////            wrapper.ne("patient_state", 9);
//            //业务代码，通过患者id查询数据库中式否有该患者，如果已存在，则不保存，跳过该患者
////            int patientCount = buiPatientInfoService.getBaseMapper().getPatientCount(wrapper);
////            if (patientCount>0){
////                list.add("在第"+row+"行的<"+patientInfo.getHealingId()+">患者已存在！！");
////                errorCount++;
////            }else {
////                boolean save = buiPatientInfoService.save(patientInfo);
////                if (save){
////                    rowSuccess++;
////                }
////            }
//
//        }
        if (list.size() > 0) {
            res.put("log", list);
        }
        res.put("success", "导入数据成功条数:" + rowSuccess);
        res.put("error", "导入数据失败条数:" + errorCount);
        long endTime = System.currentTimeMillis();
        String time = String.valueOf((endTime - startTime) / 1000);
        res.put("time", "导入数据用时:" + time + "秒");
//        renderResult(response, res);
        return CommonResult.success(excelInfoList);
    }


    @ApiOperation("添加个人企业")
    @PostMapping("/addMaintainSSS")
    public CommonResult addMaintainSSS(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam("name") String name) {
        long startTime = System.currentTimeMillis();
        List<String> list = new ArrayList();
        Map<String, Object> res = new HashMap<>();
        int row = 1;
        int rowSuccess = 0;
        Integer errorCount = 0;
        List<MaintainDto> excelInfo = ReadPatientExcelUtil.getExcelInfo(file);
        List<MaintainDto> excelInfoList = new ArrayList<>();
        excelInfo.stream().forEach(exce -> {
            MaintainDto maintainDto = new MaintainDto();
            BeanUtils.copyProperties(exce, maintainDto);
            maintainDto.setIndividual("1");//个体
            //判断是否包含该字
            boolean contains = exce.getAddress().contains(name);
            if (contains) {
                maintainDto.setCity(name);
                String[] split = exce.getAddress().split(name);
                maintainDto.setDistrict(split[1]);
            } else {
                //截取字符串 市
                boolean con = exce.getAddress().contains("市");
                if (con) {
                    String[] split = exce.getAddress().split("市");
                    String substring = split[0].substring(split[0].length() - 2, split[0].length());
                    System.out.println(substring + "市");
                    maintainDto.setDistrict(split[1]);
                    maintainDto.setCity(substring + "市");
                } else {
                    maintainDto.setDistrict(exce.getAddress());
                    maintainDto.setCity(name);
                }
            }
            excelInfoList.add(maintainDto);
        });
        maintainService.addMaintainSSS(excelInfoList);
        if (list.size() > 0) {
            res.put("log", list);
        }
        res.put("success", "导入数据成功条数:" + rowSuccess);
        res.put("error", "导入数据失败条数:" + errorCount);
        long endTime = System.currentTimeMillis();
        String time = String.valueOf((endTime - startTime) / 1000);
        res.put("time", "导入数据用时:" + time + "秒");
//        renderResult(response, res);
        return CommonResult.success(excelInfoList);
    }


    @ApiOperation("添加个人企业")
    @PostMapping("/addMaintainSSSser")
    public CommonResult addMaintainSSSser(@RequestParam(value = "file", required = false) MultipartFile file) {
        long startTime = System.currentTimeMillis();
        List<String> list = new ArrayList();
        Map<String, Object> res = new HashMap<>();
        int row = 1;
        int rowSuccess = 0;
        Integer errorCount = 0;
        List<MaintainDto> excelInfo = ReadPatientExcelUtil.getExcelInfo(file);
        List<MaintainDto> excelInfoList = new ArrayList<>();
        excelInfo.stream().forEach(exce -> {
            MaintainDto maintainDto = new MaintainDto();
            BeanUtils.copyProperties(exce, maintainDto);
            excelInfoList.add(maintainDto);
        });
        maintainService.addMaintainSSSser(excelInfoList);
        if (list.size() > 0) {
            res.put("log", list);
        }
        res.put("success", "导入数据成功条数:" + rowSuccess);
        res.put("error", "导入数据失败条数:" + errorCount);
        long endTime = System.currentTimeMillis();
        String time = String.valueOf((endTime - startTime) / 1000);
        res.put("time", "导入数据用时:" + time + "秒");
//        renderResult(response, res);
        return CommonResult.success(excelInfoList);
    }


    //    @RegisterToSMP(serviceDisplay = "预览页面PDF下载")
    @RequestMapping(value = "/DM/gwclwxsq/qygl/exportPDF$m=query.service", method = RequestMethod.POST)
    public String exportPdf(@RequestBody Maintain maintain, HttpServletResponse response) throws UnsupportedEncodingException {
        // 1.指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String filename = "车辆维修审批单.pdf";
        String path = "C:/Users/lenovo/Desktop";
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + URLEncoder.encode(filename, "UTF-8"));
        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            os = response.getOutputStream();
            // 2 读入pdf表单
            reader = new PdfReader(path + "/" + filename);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map data = new HashMap();
            data.put("commitTime", maintain.getAddress());
            data.put("driver", maintain.getPhone());
            data.put("carId", maintain.getMaintainId());
            data.put("carType", maintain.getEnterpriseName());
            data.put("repairAddress", maintain.getPhone());
            // 7遍历data 给pdf表单表格赋值
            for (Object key : data.keySet()) {
                form.setField((String) key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
//            log.info("*******************PDF导出成功***********************");
        } catch (Exception e) {
//            log.error("*******************PDF导出失败***********************");
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
